package io.kiki.sba.registry.server.clientInterface.wrapper;


import io.kiki.sba.registry.common.model.wrapper.WrapperInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class WrapperInterceptorManager {
    private static final Logger logger = LoggerFactory.getLogger(WrapperInterceptorManager.class);
    private volatile List<WrapperInterceptor> interceptorChain = Collections.EMPTY_LIST;

    public void addInterceptor(WrapperInterceptor item) {
        List<WrapperInterceptor> list = new ArrayList<>(interceptorChain.size() + 1);
        list.addAll(interceptorChain);
        list.add(item);
        list.sort(new Comp());
        this.interceptorChain = list;
        logger.info("add interceptor:{}, now={}", item.getClass(), interceptorChain);
    }


    public List<WrapperInterceptor> getInterceptorChain() {
        return interceptorChain;
    }

    static final class Comp implements Comparator<WrapperInterceptor> {
        @Override
        public int compare(WrapperInterceptor o1, WrapperInterceptor o2) {
            return o1.getOrder() - o2.getOrder();
        }
    }
}
